﻿using System;
using System.Net;
using System.Windows.Browser;

namespace SilverPortal
{
	/// <summary>
	/// Utility class for working with cookies.
	/// </summary>
	public static class CookieUtil
	{
		/// <summary>
		/// Sets a persistent cookie with far-future expiration date.
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		public static void Set(string key, string value)
		{
			string oldCookie = HtmlPage.Document.GetProperty("cookie") as String;
			DateTime expiration = DateTime.UtcNow + TimeSpan.FromDays(2000);
			string cookie = String.Format("{0}={1};expires={2}", key, value, expiration.ToString("R"));
			HtmlPage.Document.SetProperty("cookie", cookie);
		}

		/// <summary>
		/// Retrieves an existing cookie
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static string Get(string key)
		{
			string[] cookies = HtmlPage.Document.Cookies.Split(';');
			key += '=';
			foreach (string cookie in cookies)
			{
				string cookieStr = cookie.Trim();
				if (cookieStr.StartsWith(key, StringComparison.OrdinalIgnoreCase))
				{
					string[] vals = cookieStr.Split('=');

					if (vals.Length >= 2)
					{
						return vals[1];
					}

					return string.Empty;
				}
			}

			return null;
		}

		/// <summary>
		/// Deletes a specified cookie by setting its value to empty and expiration to -1 days
		/// </summary>
		/// <param name="key"></param>
		public static void DeleteCookie(string key)
		{
			string oldCookie = HtmlPage.Document.GetProperty("cookie") as String;
			DateTime expiration = DateTime.UtcNow - TimeSpan.FromDays(1);
			string cookie = String.Format("{0}=;expires={1}", key, expiration.ToString("R"));
			HtmlPage.Document.SetProperty("cookie", cookie);
		}
	}
}
